package com.visikard.ui.fragment;

import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Locale;

import android.os.Bundle;
import android.os.Message;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AbsListView;
import android.widget.AbsListView.OnScrollListener;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.TextView;

import com.visikard.application.Constant;
import com.visikard.application.UIMessage;
import com.visikard.application.VKRegApplication;
import com.visikard.asynctask.BaseTask;
import com.visikard.asynctask.GetListUserRatingTask;
import com.visikard.asynctask.GetRatingReviewTask;
import com.visikard.item.ItemAudienceKard;
import com.visikard.item.ItemCouponsBuilder;
import com.visikard.item.ItemRatingReview;
import com.visikard.system.Device;
import com.visikard.ui.R;
import com.visikard.ui.activity.CouponsRTUIMainActivity;
import com.visikard.ui.adapter.ListUserRatingAdapter;
import com.visikard.utility.BitmapUtils;
import com.visikard.utility.UILImageUtils;
import com.visikard.utility.Utils;

public class CouponReviewFragment extends BaseFragment {

	public static final String MSG_SEND_ITEM_COUPONS = "SendItemCoupons";

	ItemCouponsBuilder itemCoupons;

	private ImageView imageCoupon;
	private TextView nameCoupon, percentOff, expireDate;
	private TextView ratingEverage, totalPeople, number1, number2, number3, number4, number5;
	private ProgressBar progressStar1, progressStar2, progressStar3, progressStar4, progressStar5;
	private ViewGroup ratingGroup;
	private ImageView btnBack;
	private ListView listView;
	private View header;

	DateFormat timeFormat;
	DateFormat formatter;

	int pageIndex = 1;
	long idCampaignSpecail = -1;
	private boolean isNoLoadMore = false;
	private boolean isLoadingMore = false;

	private ListUserRatingAdapter listUserAdapter;
	ArrayList<ItemAudienceKard> listUser = new ArrayList<ItemAudienceKard>();
	ItemRatingReview itemRating = new ItemRatingReview();

	private BaseTask mAsyncTask;

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
		View view = inflater.inflate(R.layout.coupon_review_fragment, container, false);
		Bundle bundle = getArguments();
		if (bundle != null) {
			itemCoupons = (ItemCouponsBuilder) bundle.getSerializable(MSG_SEND_ITEM_COUPONS);
		}
		formatter = new SimpleDateFormat(Constant.TIME_FORMAT_STR, Locale.US);
		timeFormat = new SimpleDateFormat(Constant.TIME_FORMAT_STR_US_DATE, Locale.US);
		innitControl(view);
		getListUserRating();
		getRatingCoupons();
		return view;
	}

	private void innitControl(View view) {

		listView = (ListView) view.findViewById(R.id.listview_coupon_review);
		btnBack = (ImageView) view.findViewById(R.id.back_btn_review);

		LayoutInflater inflater = LayoutInflater.from(getActivity());
		header = inflater.inflate(R.layout.layout_header_review_rating, listView, false);

		imageCoupon = (ImageView) header.findViewById(R.id.coupon_image);
		nameCoupon = (TextView) header.findViewById(R.id.name);
		percentOff = (TextView) header.findViewById(R.id.percent_off);
		expireDate = (TextView) header.findViewById(R.id.expire_date);

		ratingEverage = (TextView) header.findViewById(R.id.review_averg);
		totalPeople = (TextView) header.findViewById(R.id.review_total_people);
		number1 = (TextView) header.findViewById(R.id.text_number1);
		number2 = (TextView) header.findViewById(R.id.text_number2);
		number3 = (TextView) header.findViewById(R.id.text_number3);
		number4 = (TextView) header.findViewById(R.id.text_number4);
		number5 = (TextView) header.findViewById(R.id.text_number5);

		progressStar1 = (ProgressBar) header.findViewById(R.id.progressBar1);
		progressStar2 = (ProgressBar) header.findViewById(R.id.progressBar2);
		progressStar3 = (ProgressBar) header.findViewById(R.id.progressBar3);
		progressStar4 = (ProgressBar) header.findViewById(R.id.progressBar4);
		progressStar5 = (ProgressBar) header.findViewById(R.id.progressBar5);

		//ratingGroup = (ViewGroup) header.findViewById(R.id.rating_bar);

		Utils.overrideFonts(header);
		listView.addHeaderView(header);
		listView.setHeaderDividersEnabled(false);

		if (itemCoupons != null) {

			LinearLayout.LayoutParams lyKard = (LinearLayout.LayoutParams) imageCoupon.getLayoutParams();
			lyKard.width = Device.getDeviceWidth();
			lyKard.height = Device.getDeviceWidth() / 2;

			idCampaignSpecail = itemCoupons.getIdCampaignSpecail();
			nameCoupon.setText(itemCoupons.getCouponName());
			percentOff.setText(itemCoupons.getTextImage1());
			String strDate = getActivity().getResources().getString(R.string.coupons_tab_expire_date);
			expireDate.setText(strDate);
			// ImageLoader.getInstance(getActivity()).loadImageCorner(imageCoupon, itemCoupons.getImageSpecial(),
			// Device.getDeviceWidth(), BitmapUtils.ROUND_NONE, 0, 0, 0, 0, 0);
			UILImageUtils.loadImage(imageCoupon, // image view
					itemCoupons.getImageSpecial(), // url
					0, // size of view
					BitmapUtils.ROUND_NONE, // round all
					0, // round size
					0, // shadow
					0, // shadow resource
					0, 0);

			expireDate.setText(getResources().getString(R.string.coupons_tab_expire_date) + " "
					+ itemCoupons.getExpireDate());
		}

		btnBack.setOnClickListener(onclick);

		if (listUserAdapter == null) {
			listUserAdapter = new ListUserRatingAdapter(getActivity(), listUser);
			listView.setAdapter(listUserAdapter);
		}
		else {
			listUserAdapter.notifyDataSetChanged();
		}

		listView.setOnScrollListener(new OnScrollListener() {

			@Override
			public void onScrollStateChanged(AbsListView view, int scrollState) {
				// TODO Auto-generated method stub

			}

			@Override
			public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {
				// For load more
				if (totalItemCount > 2 && firstVisibleItem + visibleItemCount >= totalItemCount && !isLoadingMore
						&& !isNoLoadMore) {
					pageIndex++;
					isLoadingMore = true;
					getMoreListUserRating();
					// load more
				}
			}
		});
	}

	@Override
	public void onPause() {
		super.onPause();
	}

	private void reportRating() {
		ratingEverage.setText("" + itemRating.getRatingEverage());
		totalPeople.setText("" + itemRating.getTotal());
		number1.setText("" + itemRating.getRating1());
		number2.setText("" + itemRating.getRating2());
		number3.setText("" + itemRating.getRating3());
		number4.setText("" + itemRating.getRating4());
		number5.setText("" + itemRating.getRating5());
		if (itemRating.getTotal() > 0) {
			int rating1 = (int) (itemRating.getRating1() * 100 / itemRating.getTotal());
			progressStar1.setProgress(rating1);

			int rating2 = (int) (itemRating.getRating2() * 100 / itemRating.getTotal());
			progressStar2.setProgress(rating2);

			int rating3 = (int) (itemRating.getRating3() * 100 / itemRating.getTotal());
			progressStar3.setProgress(rating3);

			int rating4 = (int) (itemRating.getRating4() * 100 / itemRating.getTotal());
			progressStar4.setProgress(rating4);

			int rating5 = (int) (itemRating.getRating5() * 100 / itemRating.getTotal());
			progressStar5.setProgress(rating5);
		}
		else {
			progressStar1.setProgress(0);
			progressStar2.setProgress(0);
			progressStar3.setProgress(0);
			progressStar4.setProgress(0);
			progressStar5.setProgress(0);
		}

		int rating = (int) itemRating.getRatingEverage();
		if (rating > 0) {
			// show rating bar small
			for (int i = 0; i < ratingGroup.getChildCount(); i++) {
				if (i <= (rating - 1)) {
					((ImageView) ratingGroup.getChildAt(i)).setImageResource(R.drawable.star_active);
				}
				else {
					((ImageView) ratingGroup.getChildAt(i)).setImageResource(R.drawable.star);
				}
			}
		}
	}

	private void getRatingCoupons() {
		mAsyncTask = new GetRatingReviewTask(mHandler);
		mAsyncTask.execute(VKRegApplication.uid, "" + idCampaignSpecail);
	}

	private void getListUserRating() {
		mAsyncTask = new GetListUserRatingTask(mHandler);
		mAsyncTask.execute("" + idCampaignSpecail, pageIndex, VKRegApplication.mPageSize);
	}

	private void getMoreListUserRating() {
		mAsyncTask = new GetListUserRatingTask(mHandler);
		mAsyncTask.execute("" + idCampaignSpecail, pageIndex, VKRegApplication.mPageSize);
	}

	OnClickListener onclick = new OnClickListener() {

		@Override
		public void onClick(View v) {
			switch (v.getId()) {
				case R.id.back_btn_review:
					((CouponsRTUIMainActivity) getActivity()).onBackPressed();
					break;
				default:
					break;
			}
		}
	};

	@SuppressWarnings("unchecked")
	@Override
	public boolean handleMessage(Message msg) {
		if (getActivity() == null)
			return false;
		switch (msg.what) {
			case UIMessage.MSG_GET_RATING_SUCCESS:
				itemRating = (ItemRatingReview) msg.obj;
				if (itemRating != null)
					reportRating();
				return true;
			case UIMessage.MSG_GET_DATA_SUCCESS:
				ArrayList<ItemAudienceKard> result = (ArrayList<ItemAudienceKard>) msg.obj;
				if (result == null || result.size() < VKRegApplication.mPageSize)
					isNoLoadMore = true;
				if (result != null && result.size() > 0) {
					listUser.addAll(result);
				}
				listUserAdapter.notifyDataSetChanged();
				isLoadingMore = false;
				return true;
		}
		return super.handleMessage(msg);
	}

}
